// pages/merchant/recharge-package/index.js
const { FormUtils } = require('../../../utils/form-config.js');
const api = require('../../../utils/api.js');

Page({
  data: {
    packages: [],
    filteredPackages: [],
    searchKeyword: '',
    showModal: false,
    showDeleteModal: false,
    isEdit: false,
    formData: {},
    isFormValid: false,
    selectedPackage: null
  },

  onLoad() {
    this.loadPackages();
  },

  onShow() {
    this.loadPackages();
  },

  // 加载充值包列表
  async loadPackages() {
    try {
      wx.showLoading({ title: '加载中...' });
      
      const result = await api.getAdminRechargePackages();
      
      if (result.code === 0) {
        // 格式化金额显示（从分转换为元）
        const formattedPackages = (result.data || []).map(pkg => ({
          ...pkg,
          displayAmount: (pkg.amount / 100).toFixed(2),
          displayBonus: (pkg.bonus / 100).toFixed(2),
          displayTotalAmount: ((pkg.amount + pkg.bonus) / 100).toFixed(2)
        }));
        
        this.setData({
          packages: formattedPackages,
          filteredPackages: formattedPackages
        });
      } else {
        throw new Error(result.msg || '获取充值包列表失败');
      }

      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'error'
      });
      console.error('加载充值包失败:', error);
    }
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.filterPackages(keyword);
  },

  // 过滤充值包
  filterPackages(keyword) {
    const { packages } = this.data;
    const filtered = packages.filter(pkg => 
      pkg.name.toLowerCase().includes(keyword.toLowerCase())
    );
    this.setData({ filteredPackages: filtered });
  },

  // 添加充值包
  onAddPackage() {
    const formData = FormUtils.initFormData('rechargePackage');
    this.setData({
      showModal: true,
      isEdit: false,
      formData,
      isFormValid: false
    });
  },

  // 编辑充值包
  onEditPackage(e) {
    const item = e.currentTarget.dataset.item;
    const formData = {
      ...item,
      amount: (item.amount / 100).toFixed(2), // 转换为元显示
      bonus: (item.bonus / 100).toFixed(2)   // 转换为元显示
    };
    
    this.setData({
      showModal: true,
      isEdit: true,
      formData,
      selectedPackage: item,
      isFormValid: true
    });
  },

  // 切换状态
  async onToggleStatus(e) {
    const item = e.currentTarget.dataset.item;
    const newStatus = item.status === 1 ? 0 : 1;
    const statusText = newStatus === 1 ? '启用' : '禁用';
    
    try {
      const result = await wx.showModal({
        title: '确认操作',
        content: `确定要${statusText}该充值包吗？`
      });
      
      if (!result.confirm) return;
      
      wx.showLoading({ title: `${statusText}中...` });
      
      const apiResult = await api.toggleRechargePackageStatus(item._id);
      
      if (apiResult.code === 0) {
        // 重新加载数据
        await this.loadPackages();
        
        wx.showToast({
          title: `${statusText}成功`,
          icon: 'success'
        });
      } else {
        throw new Error(apiResult.msg || '操作失败');
      }
      
    } catch (error) {
      console.error('切换状态失败:', error);
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'error'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 删除充值包
  onDeletePackage(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      showDeleteModal: true,
      selectedPackage: item
    });
  },

  // 确认删除
  async onConfirmDelete() {
    const { selectedPackage } = this.data;
    
    if (!selectedPackage) return;
    
    try {
      wx.showLoading({ title: '删除中...' });
      
      const result = await api.deleteRechargePackage(selectedPackage._id);
      
      if (result.code === 0) {
        // 重新加载数据
        await this.loadPackages();
        
        this.setData({
          showDeleteModal: false,
          selectedPackage: null
        });
        
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
      } else {
        throw new Error(result.msg || '删除失败');
      }
      
    } catch (error) {
      console.error('删除失败:', error);
      wx.showToast({
        title: error.message || '删除失败',
        icon: 'error'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 表单数据变化
  onFormChange(e) {
    const { formData } = e.detail;
    this.setData({ formData });
  },

  // 表单验证
  onFormValidate(e) {
    const { isValid } = e.detail;
    this.setData({ isFormValid: isValid });
  },

  // 确认保存
  async onConfirmSave() {
    if (!this.data.isFormValid) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'error'
      });
      return;
    }

    try {
      wx.showLoading({ title: '保存中...' });
      
      const { formData, isEdit, selectedPackage } = this.data;
      
      // 准备提交数据
      const submitData = {
        name: formData.name,
        amount: Math.round(parseFloat(formData.amount) * 100), // 转换为分
        bonus: Math.round(parseFloat(formData.bonus || 0) * 100), // 转换为分
        isRecommended: formData.isRecommended,
        label: formData.label,
        description: formData.description
      };
      
      let result;
      
      if (isEdit) {
        result = await api.editRechargePackage(selectedPackage._id, submitData);
      } else {
        result = await api.addRechargePackage(submitData);
      }
      
      if (result.code === 0) {
        // 重新加载数据
        await this.loadPackages();
        
        this.onCloseModal();
        
        wx.showToast({
          title: isEdit ? '保存成功' : '添加成功',
          icon: 'success'
        });
      } else {
        throw new Error(result.msg || '操作失败');
      }
      
    } catch (error) {
      console.error('保存失败:', error);
      wx.showToast({
        title: error.message || '保存失败',
        icon: 'error'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 关闭弹窗
  onCloseModal() {
    this.setData({
      showModal: false,
      formData: {},
      isFormValid: false,
      selectedPackage: null
    });
  },

  // 关闭删除确认弹窗
  onCloseDeleteModal() {
    this.setData({
      showDeleteModal: false,
      selectedPackage: null
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  }
});
